package com.ruoyi.web.controller.wechat;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.pcwl.domain.WebchatUser;
import com.ruoyi.pcwl.domain.dto.BindPhoneDto;
import com.ruoyi.pcwl.service.IWebchatUserService;
import com.ruoyi.system.service.ISysUserService;

import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

@Controller
@RequestMapping("/admin/wechat")
@CrossOrigin //跨域
public class WechatBindController {

    @Autowired
    private IWebchatUserService webchatUserService;

    @Autowired
    private WxMpService wxMpService;


    @Autowired
    private TokenService tokenService;

    @Autowired
    private ISysUserService sysUserService;

    @Value("${wechat.userInfoUrl}")
    private String userInfoUrl;

    @GetMapping("/authorize")
    public String authorize(@RequestParam("returnUrl") String returnUrl,
                            HttpServletRequest request) {
        //buildAuthorizationUrl三个参数
        //第一个参数：授权路径，在哪个路径获取微信信息
        //第二个参数：固定值，授权类型 WxConsts.OAuth2Scope.SNSAPI_USERINFO
        //第三个参数：授权成功之后，跳转路径  'sssss' 转换成  '#'
        String redirectUrl = null;
        try {
            redirectUrl = wxMpService.getOAuth2Service()
//            userInfoUrl这个路径微信公众号会带着code去调用,就是下面的userInfo方法，我们可以用code去获取用户信息,实现自己的逻辑
                    .buildAuthorizationUrl(userInfoUrl,
                            WxConsts.OAuth2Scope.SNSAPI_USERINFO,
                            URLEncoder.encode(returnUrl.replace("sssss", "#"),"utf-8"));
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        return "redirect:" + redirectUrl;
    }

//    这个方法是微信公众号调用的，我们可以用code去获取用户信息,实现自己的逻辑，并通过重定向跳转到前端页面，前端页面通过token与openId去判断用户用没有绑定手机号，是否合法用户
    @GetMapping("/userInfo")
    public String userInfo(@RequestParam("code") String code,
                           @RequestParam("state") String returnUrl) throws Exception {
        //获取accessToken
        WxOAuth2AccessToken accessToken = wxMpService.getOAuth2Service().getAccessToken(code);

        //使用accessToken获取openId
        String openId = accessToken.getOpenId();
        System.out.println("openId: "+openId);

        //获取微信用户信息
        WxOAuth2UserInfo wxMpUser = wxMpService.getOAuth2Service().getUserInfo(accessToken, null);
//        System.out.println("微信用户信息: "+JSON.toJSONString(wxMpUser));

        //根据openid查询用户表
        LambdaQueryWrapper<WebchatUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WebchatUser::getOpenId,openId);
        WebchatUser webchatUser = webchatUserService.getOne(wrapper);

        String token = getToken(webchatUser);
        if(returnUrl.indexOf("?") == -1) {
            return "redirect:" + returnUrl + "?token=" + token + "&openId=" + openId;
        } else {
            return "redirect:" + returnUrl + "&token=" + token + "&openId=" + openId;
        }
    }

    private String getToken(WebchatUser webchatUser) {
        SysUser sysUser = null;
        if (webchatUser !=null)
        {
            sysUser = sysUserService.selectUserById(Long.parseLong(webchatUser.getSysUserId()));
        }

        LoginUser loginUser = new LoginUser();
        loginUser.setUser(sysUser);
        loginUser.setUserId(sysUser.getUserId());


        String token = "";
        //判断openid是否存在
        if(sysUser != null) {

            token = tokenService.createToken(loginUser);
//            token = JwtHelper.createToken(sysUser.getId(),sysUser.getUsername());
        }
        return token;
    }

    @PostMapping("/bindPhone")
    @ResponseBody
    public AjaxResult bindPhone(@RequestBody BindPhoneDto bindPhoneDto) {

        SysUser sysUser = sysUserService.selectUserByPhone(bindPhoneDto.getPhone());

        //1 根据手机号查询数据库
//        LambdaQueryWrapper<WebchatUser> wrapper = new LambdaQueryWrapper<>();
//        wrapper.eq(WebchatUser::getPhone,bindPhoneVo.getPhone());
//        WebchatUser webchatUser = webchatUserService.getOne(wrapper);

        //2 如果存在，更新记录 openid
        if(sysUser != null) {
            WebchatUser webchatUser = new WebchatUser();
            webchatUser.setOpenId(bindPhoneDto.getOpenId());
            webchatUser.setSysUserId(sysUser.getUserId().toString());
            webchatUser.setPhone(bindPhoneDto.getPhone());
            webchatUserService.updateById(webchatUser);


//            String token = JwtHelper.createToken(sysUser.getId(),sysUser.getUsername());
            String token = getToken(webchatUser);
            return AjaxResult.success(token);
        } else {
            return AjaxResult.error("手机号不存在，请联系管理员修改");
        }
    }
}
